package grpc

import (
	"gateway/core"
	"google.golang.org/grpc/metadata"
	"protos/demo1_proto"
)

type GRPCProxy struct {
	Service string
	Method  string
}

// GRPC 的处理方法
func (p *GRPCProxy) Handle(ctx *core.Context) {
	conn, err := ctx.Gateway.GetGRPCConn(p.Service)
	if err != nil {
		ctx.JSON(500, map[string]string{"error": err.Error()})
		return
	}

	md := metadata.New(map[string]string{
		"x-forwarded-for": ctx.Request.RemoteAddr,
		"Authorization":   ctx.GetHeader("Authorization"),
	})
	newCtx := metadata.NewOutgoingContext(ctx.Request.Context(), md)

	client := demo1_proto.NewGreeterClient(conn)
	resp, err := client.Demo1Method(newCtx, &demo1_proto.HelloRequest{
		Name: "你好！",
	})

	if err != nil {
		ctx.JSON(502, map[string]string{"error": err.Error()})
		return
	}
	ctx.JSON(200, resp)
}
